<template>
    <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span>基本资料</span>
        </div>
        <!-- 表单 -->
        <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="100px">
            <el-form-item label="登录名称" prop="username">
                <el-input v-model="userForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickname">
                <el-input v-model="userForm.nickname" minlength="1" maxlength="10"></el-input>
            </el-form-item>
            <el-form-item label="用户邮箱" prop="email">
                <el-input v-model="userForm.email"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="clickSubmit">提交修改</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script>
export default {
  name: 'UserInfo',
  data () {
    return {
    //   userForm: this.$store.state.userinfo, // 有问题,修改了vuex中的state中的值

      // 两种解决方案:
      // 浅拷贝 Object.assign({},this.$store.state.userinfo)
      // userForm: Object.assign({}, this.$store.state.userinfo),
      // 展开运算符 { ...this.$store.state.userinfo }
      // userForm: { ...this.$store.state.userinfo },

      userForm: { ...this.$store.state.userinfo }, // xiaosa  => sasa
      userFormRules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称必须是1-10位的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置表单 清除错误样式
    reset () {
      this.$refs.userFormRef.resetFields()
      this.userForm = { ...this.$store.state.userinfo }
    },

    // 修改表单数据
    clickSubmit () {
      // 手动校验
      this.$refs.userFormRef.validate(async valid => {
        // 1.校验不合法 中断执行
        if (!valid) return

        // 2.axios发送请求
        const { data: res } = await this.$http.put('/my/userinfo', this.userForm)
        // console.log(res)
        // 3.修改失败
        if (res.code !== 0) return this.$message.error(res.message)

        // 4.修改成功
        this.$message.success(res.message)

        // 5.再次请求用户数据
        this.$store.dispatch('initUserInfo')
      })
    }
  }
}
</script>

<style scoped lang='less'>
 .el-form{
     width:500px;
 }
</style>
